/*
 * @Description: 核算数量和单位重量相关hook
 * @Author: chenju
 * @Date: 2022-07-13 11:07:02
 * @LastEditors: chenju
 * @LastEditTime: 2022-08-18 18:38:12
 */
import { computed, watch, toRefs } from 'vue';
import { weightUnitArr } from '@/constants/enum';
import { merge } from 'lodash';
import Decimal from 'decimal.js';
import { limitStrLength } from '@/utils';

interface UseWeightAndUnitParams<T> {
  // 入参表单
  props: T;
  // 配置
  options?: DefaultOptionsType;
  // 单位的类型变化时（重量单位/非重量单位的切换）
  onUnitTypeChange?: (isWeightUnit: boolean) => void;
}

interface ParamsPropsType {
  // 核算数量
  dosage: string;
  // 核算数量单位
  unit: string;
  // 单位重量
  weight: string;
  // 单位重量单位
  weightUnit: string;
}

interface DefaultOptionsType {
  isChangeNumWhenUnitChange: boolean;
}

const defaultOptions: DefaultOptionsType = {
  // 改变核算数量单位为重量单位时，计算核算数量的值（当前核算数量的值*单位重量）
  isChangeNumWhenUnitChange: true
};

export const useWeightAndUnit = <T extends ParamsPropsType>({
  props,
  options,
  onUnitTypeChange
}: UseWeightAndUnitParams<T>) => {
  const { dosage, unit, weight, weightUnit } = toRefs(props);
  options = merge(defaultOptions, options);

  console.log('useWeightAndUnit options', options);

  // 应该展示单位重量
  function shouldShowWeightUnit(unit: string | undefined) {
    if (!unit) return true;
    return !weightUnitArr.includes(unit);
  }

  // 是否是重量单位
  const isWeightUnitComputed = computed(() => {
    return weightUnitArr.includes(unit.value);
  });

  // 监听单位的类型变化
  watch([() => isWeightUnitComputed.value, () => unit.value], ([val, val2]) => {
    console.log('val', val, val2);
    if (val) {
      if (options?.isChangeNumWhenUnitChange) {
        // NOTE 这里会直接改变原表单中的值
        if ((weight.value || weight.value === '0') && dosage.value) {
          dosage.value = limitStrLength(
            Decimal.mul(Number(dosage.value), Number(weight.value)).toNumber(),
            6,
            true
          );
        }
      }
      weightUnit.value = unit.value;
      weight.value = '1';
    }
    onUnitTypeChange && onUnitTypeChange(val);
  });

  return {
    shouldShowWeightUnit,
    isWeightUnitComputed
  };
};
